import { LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons';
import { Avatar, Menu, Spin, message } from 'antd';
import React from 'react';
import { ConnectProps, connect, Dispatch } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from '@/models/user';
import HeaderDropdown from '../HeaderDropdown';
import styles from './index.less';

import UpdateForm from './components/UpdateForm';
import ResetPwd from './components/ResetPwd';
import SwitchOrganize from './components/SwitchOrganize';
import { updateData, updatePwd, updateSwitchOrganize } from './components/service';

const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在修改');
  try {
    await updateData(fields);
    hide();
    message.success('修改成功');

    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

export type GlobalHeaderRightProps = {
  dispatch: Dispatch;
  currentUser?: CurrentUser;
  menu?: boolean;
} & Partial<ConnectProps>;

class AvatarDropdown extends React.Component<GlobalHeaderRightProps> {
  /** 分布更新窗口的弹窗 */
  state = {
    updateModalVisible: false,
    resetPwdModalVisible: false,
    switchOrganizeModalVisible: false
  };

//   componentDidMount() { //组件渲染完成之后会调用这个方法
//     this.findOrganize();
//   }

//  findOrganize = async () => {
//     const hide = message.loading('正在查询');
//     await getLoginUser().then(res => {
//       console.log('---查询了组织---')
//       console.log(res)
//     })
//     hide();
//   }

  onMenuClick = (event: {
    key: React.Key;
    keyPath: React.Key[];
    item: React.ReactInstance;
    domEvent: React.MouseEvent<HTMLElement>;
  }) => {
    const { key } = event;

    if (key == 'userInfo') {//个人中心
      console.log('个人中心')
      this.setState({
        updateModalVisible: true
      });
    } else if (key == 'setPwd') {//密码设置
      this.setState({
        resetPwdModalVisible: true
      });
      console.log('密码设置')
    } else if (key == 'switchOrg') {//切换组织
      this.setState({
        switchOrganizeModalVisible: true
      })
      console.log('切换组织')
    }
    if (key === 'logout') {
      const { dispatch } = this.props;
      if (dispatch) {
        dispatch({
          type: 'login/logout',
        });
      }
      return;
    }
    // history.push(`/account/${key}`);
  };

  render(): React.ReactNode {
    const {
      currentUser = {
      },
      menu = true,
    } = this.props;
    const menuHeaderDropdown = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={this.onMenuClick}>
        {menu && (
          <Menu.Item key="userInfo">
            <UserOutlined />
            个人信息
          </Menu.Item>
        )}
        {menu && (
          <Menu.Item key="setPwd">
            <SettingOutlined />
            密码修改
          </Menu.Item>
        )}
        {menu && <Menu.Divider />}
        {menu && (
          <Menu.Item key="switchOrg">
            <SettingOutlined />
            组织切换
          </Menu.Item>
        )}
        {menu && <Menu.Divider />}

        <Menu.Item key="logout">
          <LogoutOutlined />
          退出登录
        </Menu.Item>
      </Menu>
    );
    return currentUser && currentUser.name ? (
      <div>
        <HeaderDropdown overlay={menuHeaderDropdown}>
          <span className={`${styles.action} ${styles.account}`}>
            <Avatar size="small" className={styles.avatar} src={currentUser.head_address} alt="avatar" />
            <span className={`${styles.name} anticon`}>{currentUser.name}</span>
          </span>
        </HeaderDropdown>
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate({ ...value, id: currentUser.id });
            // const success = await handleUpdate({...value,id:currentRow?.id});
            if (success) {
              this.setState({
                updateModalVisible: false,
              });
              const { dispatch } = this.props;
              if (dispatch) {
                dispatch({
                  type: 'user/fetchCurrent',
                });
              }
              message.success('信息修改成功。');
            }
          }}
          onCancel={() => {
            this.setState({
              updateModalVisible: false,
            });
          }}
          updateModalVisible={this.state.updateModalVisible}
          values={currentUser || {}}
        />
        <ResetPwd
          onSubmit={async (value: any) => {
            const success = await updatePwd({ ...value, ids: currentUser.id });
            if (success) {
              this.setState({
                resetPwdModalVisible : false
              })
              message.success('密码重置成功。');
            }
          }}
          onCancel={() => {
            this.setState({
              resetPwdModalVisible : false
            })
          }}
          resetPwdModalVisible={this.state.resetPwdModalVisible}
          values={currentUser || {}}
        />
         <SwitchOrganize
          onSubmit={async (value: any) => {
            const success = await updateSwitchOrganize({ ...value});
            if (success) {
              this.setState({
                switchOrganizeModalVisible : false
              })
              const { dispatch } = this.props;
              if (dispatch) {
                dispatch({
                  type: 'user/fetchCurrent',
                });
              }
              message.success('组织切换成功。');
            }
          }}
          onCancel={() => {
            this.setState({
              switchOrganizeModalVisible : false
            })
          }}
          switchOrganizeModalVisible={this.state.switchOrganizeModalVisible}
          values={currentUser || {}}
        />
        
      </div>
    ) : (
      <span className={`${styles.action} ${styles.account}`}>
        <Spin
          size="small"
          style={{
            marginLeft: 8,
            marginRight: 8,
          }}
        />
      </span>
    );
  }
}

export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,
}))(AvatarDropdown);
